package com.ruoyi.framework.web.service;

import cn.hutool.core.lang.Assert;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.biz.api.constants.Constants;
import com.ruoyi.biz.api.organization.RemoteCompanyService;
import com.ruoyi.biz.api.system.RemoteAreaService;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class CaUserDetailsServiceImpl implements CustomUserDetailService {
    private static final Logger log = LoggerFactory.getLogger(CaUserDetailsServiceImpl.class);

    private final String RANGE = "ca";
    @Autowired
    private ISysUserService userService;
    @Autowired
    private RemoteCompanyService remoteCompanyService;
    @Autowired
    private RemoteAreaService remoteAreaService;
    @Autowired
    private SysPasswordService passwordService;
    @Autowired
    private SysPermissionService permissionService;

    public static void main(String[] args) {
        String caRespJson = HttpUtil.get(String.format(UserConstants.CA_URL, "5194B4E63C2C0C58"));
        System.out.println(caRespJson);
        System.out.println(SecurityUtils.encryptPassword("Qwer123456!@#$"));
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        String caRespJson = "";
        try {
            log.info("当前登录ukey:{}", username);

            caRespJson = HttpUtil.get(String.format(UserConstants.CA_URL, username));

            Assert.isFalse(Objects.equals(caRespJson, "false"), String.format("当前登录异常，锁号[%s]，请联系管理员", username));

            log.info("当前登录ukey:{},caRespJson:{}", username, caRespJson);
        } catch (Exception e) {
            log.error("获取锁异常:{}", e.getMessage(), e);
            throw new ServiceException(e.getMessage());
        }

        try {
            SysUser user = null;
            JSONObject jsonObject = JSONObject.parseObject(caRespJson);

            log.info("当前登录ukey:{},解析响应json:{}", username, jsonObject);

//            String test = StringEscapeUtils.unescapeJava(caRespJson);
//            JSONObject jsonObject = JSONObject.parseObject(test);

//            log.info("当前登录ukey:{},解析响应json,test:{}", username, jsonObject1);

            if (Objects.isNull(jsonObject.getString("CORPCODE"))) {
                user = userService.selectUserByUserName(jsonObject.getString("IDCARD"));

                user = buildUser(jsonObject, user);

                jsonObject.put("user", user);
                remoteCompanyService.add(jsonObject);

            } else {
                user = userService.selectUserByUserName(jsonObject.getString("CORPCODE"));

                user = buildCorpUser(jsonObject, user);

                jsonObject.put("user", user);
                remoteCompanyService.add(jsonObject);
            }

            return createLoginUser(user);
        } catch (Exception e) {
            log.error("解析ca异常:{}", e.getMessage(), e);
        }
        return null;
    }

    private SysUser buildUser(JSONObject jsonObject, SysUser user) {
        if (Objects.isNull(user)) {
            user = new SysUser();
            Assert.notNull(jsonObject.getString("IDCARD"), "当前登录个人锁信息异常，请联系系统管理员");
            user.setUserName(jsonObject.getString("IDCARD"));
            user.setNickName(jsonObject.getString("PERSONNAME"));
            user.setPhonenumber(jsonObject.getString("LINKPHONE"));
            user.setPassword(SecurityUtils.encryptPassword(Constants.INIT_PASSWORD));
            user.setRemark(jsonObject.getString("LOCKNUMBER_NO"));
            userService.insertUser(user);
        }
        return user;
    }

    private SysUser buildCorpUser(JSONObject jsonObject, SysUser user) {
        Assert.notNull(jsonObject.getString("CORPCODE"), "当前登录企业锁信息异常，请联系系统管理员");
        if (Objects.isNull(user)) {
            user = new SysUser();
            user.setUserName(jsonObject.getString("CORPCODE"));
            user.setNickName(jsonObject.getString("CORPNAME"));
            R<Long> countynum = remoteAreaService.getDeptIdByAreaCode(jsonObject.getString("COUNTYNUM"));
            user.setDeptId(countynum.getData());
//            user.setDeptId(100L);
            user.setPhonenumber(jsonObject.getString("LINKPHONE"));
            user.setPassword(SecurityUtils.encryptPassword(Constants.INIT_PASSWORD));

            /**
             * ca用户登录之后通过弹出框进行赋值
             */
//            user.setRoleIds(new Long[]{101L});
            user.setRemark(jsonObject.getString("LOCKNUMBER_NO"));
            userService.insertUser(user);
        } else {
            user.setUserName(jsonObject.getString("CORPCODE"));
            user.setNickName(jsonObject.getString("CORPNAME"));
            user.setPhonenumber(jsonObject.getString("LINKPHONE"));
            user.setPassword(SecurityUtils.encryptPassword(Constants.INIT_PASSWORD));
            user.setRemark(jsonObject.getString("LOCKNUMBER_NO"));
            userService.update(user);
        }
        return user;
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }

    @Override
    public Boolean supports(String range) {
        return range.equals(RANGE);
    }
}
